﻿Imports System.IO
Imports System.Text.Json

'——— 备忘数据结构 ———
Public Class MemoItem
    Public Property Id As String = Guid.NewGuid().ToString("N")
    Public Property Text As String
    Public Property CreatedAt As DateTime = DateTime.Now
    Public Property IsCompleted As Boolean
End Class

'——— 备忘持久化与操作 ———
Public Class MemoStore
    Private Shared ReadOnly dataDir As String = TaskInfo.todoDataPath
    Private Shared ReadOnly dataFile As String = Path.Combine(dataDir, "memos.json")
    Private Shared _memos As List(Of MemoItem)

    Public Shared Event MemosChanged()

    Shared Sub New()
        LoadFromDisk()
    End Sub

    Public Shared ReadOnly Property Memos As List(Of MemoItem)
        Get
            If _memos Is Nothing Then _memos = New List(Of MemoItem)
            Return _memos
        End Get
    End Property

    Public Shared Sub Add(m As MemoItem)
        Memos.Add(m)
        SaveAndNotify()
    End Sub

    Public Shared Sub Update(m As MemoItem)
        Dim idx = Memos.FindIndex(Function(x) x.Id = m.Id)
        If idx >= 0 Then
            Memos(idx) = m
            SaveAndNotify()
        End If
    End Sub

    Public Shared Sub Remove(id As String)
        Dim idx = Memos.FindIndex(Function(x) x.Id = id)
        If idx >= 0 Then
            Memos.RemoveAt(idx)
            SaveAndNotify()
        End If
    End Sub

    Public Shared Function FindById(id As String) As MemoItem
        Return Memos.FirstOrDefault(Function(x) x.Id = id)
    End Function

    Public Shared Sub LoadFromDisk()
        Try
            If File.Exists(dataFile) Then
                Dim json = File.ReadAllText(dataFile)
                _memos = JsonSerializer.Deserialize(Of List(Of MemoItem))(json, New JsonSerializerOptions With {.PropertyNameCaseInsensitive = True})
                If _memos Is Nothing Then _memos = New List(Of MemoItem)
            Else
                _memos = New List(Of MemoItem)
            End If
            RaiseEvent MemosChanged()
        Catch ex As Exception
            MessageBox.Show("读取备忘数据失败：" & ex.Message)
            _memos = New List(Of MemoItem)
        End Try
    End Sub

    Private Shared Sub SaveAndNotify()
        Try
            If Not Directory.Exists(dataDir) Then Directory.CreateDirectory(dataDir)
            Dim json = JsonSerializer.Serialize(Memos, New JsonSerializerOptions With {.WriteIndented = True})
            File.WriteAllText(dataFile, json)
        Catch ex As Exception
            MessageBox.Show("保存备忘数据失败：" & ex.Message)
        End Try
        RaiseEvent MemosChanged()
    End Sub
End Class

